package com.android.baseconfig.base;

import android.app.Activity;
import android.content.Context;

import java.lang.ref.WeakReference;

import androidx.fragment.app.Fragment;

public abstract class BasePresenter<V extends BaseView> {
    public final static String TAG = BasePresenter.class.getSimpleName();
    protected V view;
    protected Context context;
    /**
     * 持有UI接口的弱引用
     */
    protected WeakReference<V> mViewRef;

    public BasePresenter() {

    }

    public BasePresenter(V view, Context context) {
        this.view = view;
        this.context = context;
    }

    /**
     * 绑定
     *
     * @param view
     */
    public void attachView(V view) {
        mViewRef = new WeakReference<V>(view);
    }

    /**
     * 解绑
     */
    public void detachView() {
        if (mViewRef != null) {
            mViewRef.clear();
            mViewRef = null;
        }
    }

    /**
     * 返回当前持有的View
     *
     * @return
     */
    public V getView() {
        return mViewRef == null ? null : mViewRef.get();
    }

    /**
     * 判断当前的View是否被销毁
     *
     * @return
     */
    public boolean isAttach() {
        if (mViewRef == null) {
            return false;
        }
        final V view = mViewRef.get();
        if (view == null) {
            return false;
        }
        boolean isAttach = true;
        if (view instanceof Activity) {
            isAttach = !((Activity) view).isFinishing();
        } else if (view instanceof Fragment) {
            isAttach = !((Fragment) view).isRemoving();
        } else if (view instanceof Fragment) {
            isAttach = !((Fragment) view).isRemoving();
        }
        return isAttach;
    }

    /**
     * 初始化Presenter的数据.比如初始化Model.
     */
    public abstract void init();

    /**
     * View开始.对应View的生命周期方法.
     */
    public void start() {

    }

    public void onCreate() {
    }

    public void onDestroy() {
    }

    public void destroy() {
    }

}
